package com.ruoyi.merchant.controller;


import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 文件上传
 *
 * @author chengxin.ju
 *
 */
@Slf4j
@RestController
@RequestMapping("/fileupload")
public class FileUploadController extends BaseController {

    /**
     * 允许上传图片后缀名
     */
    @Value("#{'${fileupload.allowedSuffix}'.split(',')}")
    private List<String> allowedSuffix;
    @Value("${domain.url}")
    private String DOMAIN_IMG_URL;
    @Value("${img.url}")
    private String url;



    /**
     * 图片上传
     *
     *
     */
    @RequestMapping("/upLoadFile")
    public AjaxResult upLoadFiles(HttpServletRequest request) throws Exception {
        String fileUrl = "";
        int index = 0 ;
        FileOutputStream fileOutputStream = null;
        FileInputStream fileInputStream = null;
        try {

            List<MultipartFile> multipartFiles = extractedFiles(request);
            if (CollectionUtils.isEmpty(multipartFiles)) {
                return error("没有检测到文件存在");
            }

            for (MultipartFile multipartFile:multipartFiles ) {
                index = multipartFile.getOriginalFilename().lastIndexOf('.') + 1;
                String fileType = multipartFile.getOriginalFilename().substring(index);
                // 组织文件名
                if (fileType!=null && !fileType.equals("") && !allowedSuffix.contains(fileType.toLowerCase())) {
                    return error("非法的文件后缀");
                }
                File folder = new File(url);
                if (!folder.exists()) {
                    folder.mkdir();
                }

                fileUrl = UUID.fastUUID() + "." + fileType;
                String fileStr = url + "/" + fileUrl ;
                fileOutputStream = new FileOutputStream(fileStr);
                fileInputStream = (FileInputStream) multipartFile.getInputStream();
                final FileChannel channel = fileInputStream.getChannel();

                ByteBuffer byteBuffer = ByteBuffer.allocate(fileInputStream.available());

                channel.read(byteBuffer);

                //byteBuffer 进行反转
                byteBuffer.flip();
                fileOutputStream.getChannel().write(byteBuffer);

                log.info("文件上传完毕：{}",fileUrl);
            }

        }catch (Exception e){
            log.error("upLoadFile",e);
            throw e;
        }finally {

            if (fileInputStream!=null){
                fileInputStream.close();
            }
            if (fileOutputStream!=null){
                fileOutputStream.close();
            }

        }

        return success(DOMAIN_IMG_URL + "/" + fileUrl);
    }

    /**
     * 提取文件
     *
     * @param request
     * @return
     */
    private List<MultipartFile> extractedFiles(HttpServletRequest request) {
        List<MultipartFile> multipartFiles = new ArrayList<>();
        // 创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            // 转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                // 记录上传过程起始时的时间，用来计算上传时间
                long pre = System.currentTimeMillis();
                // 取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if (file != null) {
                    multipartFiles.add(file);
                    // 记录上传该文件后的时间
                    long finaltime = System.currentTimeMillis();
                }
            }
        }
        return multipartFiles;
    }

}
